package com.zhugang.week07;

/**
 * @program algorithms
 * @description: diameterOfBinaryTree
 * @author: chanzhugang
 * @create: 2022/07/28 17:08
 */
public class DiameterOfBinaryTree {

    /**
     * 543 二叉树的直径
     *
     * @param root
     * @return
     */
    private int result = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        // 直径：任意两个节点路径长度中的最大值
        // 转为求树的高度
        callMaxHeight(root);
        return result;
    }

    private int callMaxHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int maxLeftHeight = callMaxHeight(root.left);
        int maxRightHeight = callMaxHeight(root.right);
        int diameter = maxLeftHeight + maxRightHeight;
        if (diameter > result) {
            // 最大的
            result = diameter;
        }
        return Math.max(maxLeftHeight, maxRightHeight) + 1;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}